package com.jiangcheng.demo.service.impl;

import com.jiangcheng.demo.entity.Liked;
import com.jiangcheng.demo.mapper.LikedMapper;
import com.jiangcheng.demo.service.LikedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangcheng.demo.utils.LikedVo;
import com.jiangcheng.demo.utils.NewResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-09-13
 */
@Service
public class LikedServiceImpl extends ServiceImpl<LikedMapper, Liked> implements LikedService {
    @Resource
    LikedMapper likedMapper;

    @Override
    public NewResult addLike(Liked liked) {
        System.out.println(liked);
        // 先查询是否有该条数据
        Liked exists = likedMapper.findExists(liked.getObjId(), liked.getLikeType(), liked.getUId());
        // 如果没有该条数据才删除
        if (exists == null) {
            // 往表中添加一条数据
            int insert = likedMapper.insert(liked);
            if (insert != 1) {
                return new NewResult(400,false,"点赞失败");
            }
            return new NewResult(200,false,"点赞成功");
        }

        return new NewResult(200,true,"点赞成功");
    }

    @Override
    public NewResult delete(Integer likeId) {
        System.out.println(likeId);
        // 先查询是否有该条数据
        Liked exists = likedMapper.selectById(likeId);
        // 如果有该条数据才删除
        if (exists != null) {
            int i = likedMapper.deleteById(likeId);
            if (i != 1) {
                return new NewResult(400,false,"取消点赞失败");
            }
            return new NewResult(400,false,"取消点赞成功");
        }

        return new NewResult(200,true,"取消点赞成功");
    }

    @Override
    public LikedVo findLikeNumByObjId(Integer objId,Integer type,Integer uId) {
        System.out.println("对象ID:" + objId + " 类型:" + type  +  " 用户ID:" + uId);
        Integer count = likedMapper.count(objId, type);
        // 查询当前对象是否有当前登录用户
        Liked exists = likedMapper.findExists(objId, type, uId);
        LikedVo likedVo = new LikedVo();
        likedVo.setCount(count);
        likedVo.setExists(false);
        if (exists != null) {
            likedVo.setExists(true);
        }
        System.out.println(exists);
        System.out.println(likedVo);
        return likedVo;
    }
}
